import axios from "axios";
import config from "./config";
import md5 from "js-md5";

axios.defaults.baseURL = config.baseUrl;
axios.defaults.withCredentials = false;

axios.interceptors.request.use(
  function(conf) {
    let authInfo = JSON.parse(localStorage.getItem(config.authInfo) || "{}");
    if (conf.url.startsWith("/cauth")) {
      // 用于非常登录认证的用户访问地址
      let appKey = "coconut_app_client_uyhloh";
      let appSecret = "coconut_app_secret_qfceta";
      let timespan = parseInt(new Date().getTime() / 1000 + "");
      conf.headers["appKey"] = appKey;
      conf.headers["timespan"] = timespan;
      conf.headers["token"] = md5(appKey + timespan + appSecret);
    } else {
      // 用于登录用户的token
      conf.headers["token"] = authInfo.token || "";
    }
    return conf;
  },
  function(err) {
    console.log(err);
    return Promise.reject(err);
  }
);

axios.interceptors.response.use(
  function(res) {
    if (res.data.code === "login") {
      localStorage.removeItem(config.authInfo);
    }
    return res;
  },
  function(err) {
    console.log(err);
    return Promise.reject(err);
  }
);
